<template>
  <BaseDialog v-model="dialogVisible" :title="title" width="900px" :before-close="handleClose">
    <el-descriptions v-loading="viewLoading" :column="4" border :label-width="140">
      <el-descriptions-item :span="4" width="200">
        <template #label>团号</template>
        {{ formData.code || '--' }}
      </el-descriptions-item>
      <el-descriptions-item width="200">
        <template #label>线路类别</template>
        <span>{{
          g_options.getOptionText(
          g_options.groupPeriodTypeOptions,
          formData.type,
          '--'
          )
          }}</span>
      </el-descriptions-item>
      <el-descriptions-item width="200">
        <template #label>{{ $t('travelAgency.routeName') }}</template>
        {{ formData.routeName || '--' }}
      </el-descriptions-item>
      <el-descriptions-item width="200">
        <template #label>{{ $t('travelAgency.routeType') }}</template>
        <span>{{
          g_options.getOptionText(
          g_options.routeTypeOptions,
          formData.routeType,
          '--'
          )
          }}</span>
      </el-descriptions-item>
      <el-descriptions-item width="200">
        <template #label>计划总数</template>
        {{ formData.peopleCountPlan ?? '--' }}
      </el-descriptions-item>
      <!-- <el-descriptions-item width="200">
        <template #label>领队</template>
        {{ formData.code || '--' }}
      </el-descriptions-item> -->
      <el-descriptions-item width="200">
        <template #label>可售</template>
        {{ formData.peopleCountPlan ?? '--' }}
      </el-descriptions-item>
      <el-descriptions-item width="200">
        <template #label>计划余位</template>
        {{ formData.remain ?? '--' }}
      </el-descriptions-item>
      <!-- <el-descriptions-item width="200">
        <template #label>预留</template>
        {{ formData.peopleCountReal || '--' }}
      </el-descriptions-item> -->
      <el-descriptions-item width="200">
        <template #label>确认</template>
        {{ formData.peopleCountReal ?? '--' }}
      </el-descriptions-item>
      <el-descriptions-item width="200">
        <template #label>出团日期</template>
        {{
        formData.startTime
        ? g_dayjs(formData.startTime).format('YYYY-MM-DD HH:mm:ss')
        : '--'
        }}
        {{
        g_options.getOptionText(
        g_options.dateDayOptions,
        g_dayjs(formData.startTime).day(),
        '--'
        )
        }}
      </el-descriptions-item>
      <el-descriptions-item width="200">
        <template #label>天数</template>
        {{ formData.days || '--' }}
      </el-descriptions-item>
      <el-descriptions-item width="200">
        <template #label>回团日期</template>
        {{
        formData.startTime
        ? g_dayjs(
        new Date(formData.startTime) * 1 +
        formData.days * 24 * 60 * 60 * 1000
        ).format('YYYY-MM-DD HH:mm:ss')
        : '--'
        }}
        {{
        g_options.getOptionText(
        g_options.dateDayOptions,
        g_dayjs(
        new Date(formData.startTime) * 1 +
        formData.days * 24 * 60 * 60 * 1000
        ).day(),
        '--'
        )
        }}
      </el-descriptions-item>
    </el-descriptions>
    <div class="tabs-container">
      <el-tabs v-model="tabValue" style="flex: 1" @tab-change="handleTabChange">
        <el-tab-pane v-for="item in g_options.lineTypeOptions" :key="item.value" :name="item.value"
          :label="item.label" />
      </el-tabs>
      <!-- <el-button type="primary" style="margin-left: 10px" @click="handleAiPlan"
        >智能规划</el-button
      > -->
      <el-button type="primary" style="margin-left: 10px" @click="handleEnter">录入</el-button>
      <el-button type="primary" style="margin-left: 10px" @click="handleQuote">导入</el-button>
    </div>
    <div class="four-border-blueBg">
      <div class="statistics-wrap">
        <div class="child-item">
          <div class="text">成本合计</div>
          <div class="number">{{ totalCost }}元</div>
        </div>
        <div class="child-item">
          <div class="text">已审核成本总计</div>
          <div class="number">{{ reviewedCost }}元</div>
        </div>
        <div class="child-item">
          <div class="text">未审核成本合计</div>
          <div class="number">{{ unreviewedCost }}元</div>
        </div>
      </div>
    </div>
    <BaseTable v-loading="contentTableLoading" ref="refContentTable" :data="contentTable" row-key="id"
      style="margin: 10px 0" max-height="300px">
      <TableColumn prop="type" label="类型" :column-width="columnWidthObj.type">
        <template #default="{ row }">
          <span :class="
              g_options.getOptionText(
                g_options.inquiryCoseTypeOptions,
                row.type,
                '--'
              )
            ">{{
            g_options.getOptionText(
            g_options.inquiryCoseTypeOptions,
            row.type,
            '--'
            )
            }}</span>
        </template>
      </TableColumn>
      <TableColumn prop="status" label="状态" :column-width="columnWidthObj.status">
        <template #default="{ row }">
          <span :class="
              g_options.getOptionText(
                g_options.costStatusOptions,
                row.status,
                '--'
              )
            ">{{
            g_options.getOptionText(
            g_options.costStatusOptions,
            row.status,
            '--'
            )
            }}</span>
        </template>
      </TableColumn>
      <TableColumn prop="summary" label="费用摘要" :column-width="columnWidthObj.summary" />
      <TableColumn prop="supplierName" label="供应商" :column-width="columnWidthObj.supplierName"></TableColumn>
      <!-- <TableColumn
        prop="summary"
        label="费用明细"
        :column-width="columnWidthObj.summary"
      /> -->
      <TableColumn prop="origCurrPrice" label="原币金额" :column-width="columnWidthObj.origCurrPrice" />
      <TableColumn prop="currency" label="币种" :column-width="columnWidthObj.currency" />
      <TableColumn prop="exRate" label="汇率" :column-width="columnWidthObj.exRate" />
      <TableColumn prop="principalPrice" label="本币金额" :column-width="columnWidthObj.principalPrice" />
      <TableColumn prop="remark" label="备注说明" :column-width="columnWidthObj.remark" />
      <TableColumn prop="action" fixed="right" :label="$t('public.action')" max-width="220"
        :column-width="columnWidthObj.action">
        <template #default="{ row }">
          <el-button text @click="handleEditDialog(row)">
            {{ $t('public.edit') }}
          </el-button>
          <el-button text @click="handleDelete(row)">
            {{ $t('public.delete') }}
          </el-button>
        </template>
      </TableColumn>
    </BaseTable>
    <el-button v-if="tabValue === '3'" type="primary" @click="handleInquiry">{{
      $t('travelAgency.makeInquiry')
      }}</el-button>
    <BaseTable v-if="tabValue === '3'" v-loading="customerLoading" ref="refCustomerTable" :data="customerTableData"
      row-key="id" style="margin: 10px 0" max-height="300px">
      <TableColumn prop="merchantNickName" label="客户名称" :column-width="customerColumnWidth.merchantNickName" />
      <TableColumn prop="status" :label="$t('fleet.orderStatus')" :column-width="customerColumnWidth.status">
        <template #default="{ row }">
          <span class="dot-status" :class="
              g_options.getOptionText(
                g_options.inquiryOrderStatusOptions,
                row.status,
                '--',
                'class'
              )
            ">{{
            g_options.getOptionText(
            g_options.inquiryOrderStatusOptions,
            row.status,
            '--'
            )
            }}</span>
        </template>
      </TableColumn>
      <TableColumn prop="startTime" :label="$t('public.startTime')" :column-width="customerColumnWidth.startTime" />
      <TableColumn prop="endTime" :label="$t('public.endTime')" :column-width="customerColumnWidth.endTime" />
      <TableColumn prop="merchantUserName" :label="$t('public.userName')"
        :column-width="customerColumnWidth.merchantUserName" />
      <TableColumn prop="merchantPrice" :label="$t('travelAgency.price')"
        :column-width="customerColumnWidth.merchantPrice" />
      <TableColumn prop="action" fixed="right" :label="$t('public.action')" max-width="220"
        :column-width="customerColumnWidth.action">
        <template #default="{ row }">
          <el-button text :disabled="row.status + '' === '4' || row.status + '' === '5'"
            @click="handleCustomerConfirm(row)">确认询价</el-button>
          <!-- <el-button text @click="handleEditDialog(row)">取消</el-button> -->
          <el-button text :disabled="row.status + '' === '4' || row.status + '' === '5'"
            @click="handleCustomerCancel(row)">
            {{ $t('public.delete') }}
          </el-button>
        </template>
      </TableColumn>
    </BaseTable>
    <BasePagination v-model:page-size="pageSize" v-model:current-page="pageNum" :total="total"
      @change="getAskOrderList()" />
    <template #footer>
      <div class="detail-dialog-footer">
        <el-button plain @click="handleClose">{{
          $t('public.close')
          }}</el-button>
        <el-button v-if="type === 'confirm'" plain type="primary" @click="handleConfirm">{{ $t('public.confirm')
          }}</el-button>
      </div>
    </template>
  </BaseDialog>

  <CostInquiryDialog v-if="inquiryVisible" v-model="inquiryVisible" :id="props.id" :type="inquiryType"
    :travel-list="travelList" @update="handleInquiryFormCb" />
  <AddOrEditCostDialog v-if="addOrEditVisible" v-model="addOrEditVisible" :id="props.id" :type="addOrEditType"
    :row="addOrEditRow" @update="handleQuery" />
  <selectQuote v-if="quoteListVisible" v-model="quoteListVisible" :id="props.id" @select="selectChange" />
</template>

<script setup>
import CostInquiryDialog from './CostInquiryDialog.vue'
import selectQuote from './selectQuote.vue'
import AddOrEditCostDialog from './AddOrEditCostDialog.vue'

const props = defineProps({
  type: {
    type: String,
    default: 'view' // view | confirm
  },
  id: {
    type: String,
    default: ''
  }
})

const quoteListVisible = ref(false)
const emit = defineEmits(['update'])
const dialogVisible = defineModel({
  type: Boolean,
  default: false
})

const title = computed(() =>
  props.type === 'confirm' ? g_t('travelAgency.groupPeriodConfirm') : '团期成本'
)
const viewLoading = ref(false)
const formData = ref({
  tripList: []
})
const tabValue = ref(g_options.lineTypeOptions[0].value)
// 询价单类型字段映射
const inquiryType = computed(() => {
  return (
    {
      2: 'hotel',
      3: 'car',
      4: 'ticket'
    }[tabValue.value] || ''
  )
})

// 成本合计
const totalCost = computed(() => {
  return contentTable.value.reduce((acc, cur) => {
    return acc + (cur.principalPrice || 0)
  }, 0)
})
// 已审核成本总计
const reviewedCost = computed(() => {
  return contentTable.value.reduce((acc, cur) => {
    return cur.status + '' === '2' ? acc + (cur.principalPrice || 0) : acc
  }, 0)
})
// 未审核成本合计
const unreviewedCost = computed(() => {
  return contentTable.value.reduce((acc, cur) => {
    return cur.status + '' === '1' ? acc + (cur.principalPrice || 0) : acc
  }, 0)
})
// 表格参数
const contentTableLoading = ref(false)
const refContentTable = ref(null)
const contentTable = ref([])
const columnWidthObj = ref({})
// 表格2
const customerLoading = ref(false)
const refCustomerTable = ref(null)
const customerTableData = ref([])
const customerColumnWidth = ref({})
const total = ref(0)
const pageSize = ref(10)
const pageNum = ref(1)
// 弹框参数
const inquiryVisible = ref(false)
const travelList = ref([])
const addOrEditVisible = ref(false)
const addOrEditType = ref('add')
const addOrEditRow = ref({})

watch(
  () => contentTable.value,
  nv => {
    useTableColumnWidth({
      refTable: refContentTable.value
    }).getTableColumnWidth(data => {
      columnWidthObj.value = data
    })
  },
  {
    // immediate: true,
    deep: true
  }
)

watch(
  () => customerTableData.value,
  nv => {
    useTableColumnWidth({
      refTable: refCustomerTable.value
    }).getTableColumnWidth(data => {
      customerColumnWidth.value = data
    })
  },
  {
    // immediate: true,
    deep: true
  }
)

onMounted(() => {
  getFormData()
  getTeamCostList()
  getAskOrderList()
})

const selectChange = (row) => {
  g_api.travelAgency.apiTeamCostImports(row.id).then(({ code, data }) => {
    if (code === '200' && data) {
      getTeamCostList()
    }
  })
}

const getFormData = () => {
  viewLoading.value = true
  g_api.travelAgency
    .apiTeamDetail({ id: props.id })
    .then(({ code, data }) => {
      if (code === '200' && data) {
        formData.value = data
      }
    })
    .finally(_ => {
      viewLoading.value = false
    })
}

const getTeamCostList = () => {
  contentTableLoading.value = true
  contentTable.value = []
  g_api.travelAgency
    .apiTeamCostList({
      pageNum: 1,
      pageSize: 100,
      type: tabValue.value === '8' ? '' : tabValue.value,
      teamId: props.id
    })
    .then(({ code, data }) => {
      if (code === '200' && data) {
        total.value = data.total
        contentTable.value = data.items
      }
    })
    .finally(_ => {
      contentTableLoading.value = false
    })
}

const getAskOrderList = () => {
  customerLoading.value = true
  customerTableData.value = []
  g_api.travelAgency
    .apiTeamAskOrderList({
      pageNum: pageNum.value,
      pageSize: pageSize.value,
      type: inquiryType.value,
      teamId: props.id
    })
    .then(({ code, data }) => {
      if (code === '200' && data) {
        total.value = data.total
        customerTableData.value = data.items
      }
    })
    .finally(_ => {
      customerLoading.value = false
    })
}

const handleAiPlan = _ => {
  //
}

const handleEnter = _ => {
  addOrEditVisible.value = true
  addOrEditType.value = 'add'
}

const handleQuote = () => {
  quoteListVisible.value = true
}

const handleQuery = () => {
  pageNum.value = 1
  getTeamCostList()
}

const handleEditDialog = row => {
  addOrEditVisible.value = true
  addOrEditType.value = 'edit'
  addOrEditRow.value = row
}

const handleDelete = row => {
  g_utils
    .deleteConfirm()
    .then(() => {
      contentTableLoading.value = true
      g_api.travelAgency
        .apiTeamCostDelete({
          id: row.id
        })
        .then(res => {
          if (res.code === '200') {
            ElMessage.success(res.message)
            handleQuery()
          }
        })
        .finally(() => {
          contentTableLoading.value = false
        })
    })
    .catch(() => { })
}

const handleTabChange = _ => {
  getTeamCostList()
  getAskOrderList()
}

const handleInquiry = () => {
  inquiryVisible.value = true
  travelList.value = JSON.parse(JSON.stringify(formData.value.tripList)).map(
    item => {
      item.peopleCount = formData.value.peopleCountPlan
      return item
    }
  )
}

const handleInquiryFormCb = data => {
  getAskOrderList()
}

const askOrderUpdate = (row, status) => {
  customerLoading.value = true
  g_api.travelAgency
    .apiTeamAskOrderUpdate({
      id: row.id,
      merchantOrderId: row.merchantOrderId,
      status
    })
    .then(res => {
      if (res.code === '200') {
        ElMessage({
          message: res.message,
          type: 'success'
        })
        getAskOrderList()
      }
    })
    .finally(_ => {
      customerLoading.value = false
    })
}
const handleCustomerConfirm = row => {
  askOrderUpdate(row, 3)
}

const handleCustomerCancel = row => {
  g_utils
    .deleteConfirm()
    .then(() => {
      askOrderUpdate(row, 5)
    })
    .catch(() => { })
}

const handleClose = () => {
  dialogVisible.value = false
}

const handleConfirm = () => {
  g_api.travelAgency
    .apiTeamUpdateStatus({
      id: props.id,
      status: 3
    })
    .then(res => {
      if (res.code === '200') {
        ElMessage({
          message: res.message,
          type: 'success'
        })
        handleClose()
        emit('update')
      }
    })
}
</script>

<style scoped lang="scss">
.tabs-container {
  display: flex;
  justify-content: space-between;
  align-items: center;

  :deep(.el-tabs__nav.is-top) {
    width: 100%;
    justify-content: space-around;
  }
}

.statistics-wrap {
  display: flex;
  flex-wrap: wrap;
  padding: 10px;
  background-color: var(--menu-theme-bg);

  .child-item {
    flex: 1;
    position: relative;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    padding: 0 10px;
    border-radius: 5px;

    +.child-item {
      &::before {
        content: '';
        position: absolute;
        left: 0;
        top: 50%;
        transform: translateY(-50%);
        display: block;
        width: 1px;
        height: 36px;
        background-color: #e5e5e5;
      }
    }

    .text {
      font-size: 14px;
      color: var(--device-statistics-text-color);
    }

    .number {
      margin-top: 4px;
      font-size: 24px;
      color: var(--device-statistics-text-color2);
      font-weight: bold;
    }
  }
}
</style>
